package alipushclient

import (
	"errors"
	"strings"
)

const (
	BaseURL = "https://cloudpush.aliyuncs.com/"
)

type PushClient struct {
	Region          string
	AccessKeyID     string
	AccessKeySecret string
	BaseUrl         string
}

func NewPushClient(region, accessKeyID, accessKeySecret string) *PushClient {
	pusher := &PushClient{region, accessKeyID, accessKeySecret, BaseURL}
	return pusher
}

func (client *PushClient) PushAndroidNotice(notice *AndroidNotice) (string, error) {
	payload := NewPushPayLoad()
	payload.SetAndroidNotice(notice)
	content, _ := payload.AndroidNoticeToBytes(client.Region, client.AccessKeyID, client.AccessKeySecret)

	return client.Send(content)
}

func (client *PushClient) PushIOSNotice(notice *IOSNotice) (string, error) {
	payload := NewPushPayLoad()
	payload.SetIOSNotice(notice)
	content, _ := payload.IOSNoticeToBytes(client.Region, client.AccessKeyID, client.AccessKeySecret)

	return client.Send(content)
}

func (this *PushClient) Send(data []byte) (string, error) {
	return this.SendGetBytes(data)
}

func (this *PushClient) SendGetBytes(content []byte) (string, error) {
	ret, err := SendGetBytes(this.BaseUrl, content)
	if err != nil {
		return ret, err
	}

	if strings.Contains(ret, "ResponseId") {
		return ret, nil
	} else {
		return "", errors.New(ret)
	}
}
